import { map, find } from "lodash";
import React from "react";
import PropTypes from "prop-types";
import { useDebouncedCallback } from "use-debounce";
import { Section, Select } from "@/components/visualizations/editor";
import Renderer from "@/visualizations/chart/Renderer";
// import { axios } from "@/services/axios";

function Editor({ column, onChange, query }) {
  const [onChangeDebounced] = useDebouncedCallback(onChange, 200);
  
  return (
    <Section>
      <label>自定义视图/动画</label>  
      <Select
        placeholder="请选择自定义视图/动画"
        defaultValue={column.customVisualizationId || ''}
        onChange={value => {
          onChangeDebounced({ customVisualizationId: value });
        }}
      >
        <Option key=''>-无-</Option>
        {map(query.visualizations, (vis)=> (vis.type === 'CHART' && (vis.options.globalSeriesType==='custom' || vis.options.globalSeriesType==='echarts' || vis.options.globalSeriesType==='three')) && (
            <Option key={vis.id}>{vis.name}</Option>
        ))}
      </Select>
    </Section>
  );
}

Editor.propTypes = {
  column: PropTypes.shape({
    name: PropTypes.string.isRequired,
    customvisualizationId: PropTypes.string,
  }).isRequired,
  onChange: PropTypes.func.isRequired,
};

export default function initCustomColumn(column, {...props}) {
  const { visualizations } = props;
  let vis = null;

  // const [vis, setVis] = useState(null);
  // useEffect(()=>{
  //   if (!!column.customVisualizationId) {
  //     if (visualizations) {
  //       setVis(find(visualizations, item => item.id === parseInt(column.customVisualizationId)));
  //     } else {
  //       axios.get('api/visualizations/' + column.customVisualizationId).then(v=> setVis(v));
  //     }
  //   }
  // }, [column])

  function prepareData(row) {
    if (!!column.customVisualizationId && visualizations) {
      vis = find(visualizations, item => item.id === parseInt(column.customVisualizationId));
    }
    
    return {
      text: row[column.name],
    };
  }

  function CustomColumn({ row, index }) {
    // eslint-disable-line react/prop-types
    const { text } = prepareData(row);

    if (!!column.customVisualizationId && vis) {
      return <Renderer 
        key={`visualization${vis.id}${index}`}
        options={vis.options} 
        visualizationName={vis.name}
        row={row}
        {...props}
      />
    } else {
      return text;
    }
  }

  CustomColumn.prepareData = prepareData;

  return CustomColumn;
}

initCustomColumn.friendlyName = "自定义代码视图";
initCustomColumn.Editor = Editor;
